package edu.ynu.se.xiecheng.achitectureclass.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class YingShiTokenService {

    // API配置直接写在代码中
    private static final String API_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken";
    private static final String ACCOUNT_ID = "1ca7f0ab24ba41b291346347ec30140e";  // 实验提供的accountId

    private String accessToken;
    private long tokenExpiryTime;

    // 获取token
    public String getAccessToken() {
        // 如果token有效，直接返回
        if (accessToken != null && System.currentTimeMillis() < tokenExpiryTime) {
            return accessToken;
        }

        // 否则重新获取token
        fetchNewToken();
        return accessToken;
    }

    // 获取新token
    private void fetchNewToken() {
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求体
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode body = mapper.createObjectNode();
        body.put("accountId", ACCOUNT_ID);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> requestEntity = new HttpEntity<>(body.toString(), headers);

        // 发起POST请求
        ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, requestEntity, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            try {
                // 解析返回的JSON
                JsonNode jsonNode = mapper.readTree(response.getBody());

                // 获取accessToken和expireTime
                JsonNode dataNode = jsonNode.get("data");
                if (dataNode != null) {
                    accessToken = dataNode.get("accessToken").asText();
                    long expireTime = dataNode.get("expireTime").asLong();

                    // 设置token过期时间
                    tokenExpiryTime = expireTime;
                } else {
                    throw new RuntimeException("获取token失败，返回数据不符合预期");
                }
            } catch (Exception e) {
                throw new RuntimeException("获取token失败", e);
            }
        } else {
            throw new RuntimeException("获取token时请求失败，状态码：" + response.getStatusCode());
        }
    }
}
